﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Forums.OfflineStore;
using System.Collections.ObjectModel;
using System.Data.Linq;
using Threading = System.Threading;
using System.ComponentModel;
using System.Windows.Threading;

namespace Microsoft.Forums.ForumsClient.Models
{
    /// <summary>
    /// A container for a post that will be displayed on the UI
    /// This wraps child posts in ObserableCollections and provides 
    /// ability to update data
    /// </summary>
    public class ThreadedPostViewModel : PostViewModel
    {
        bool hasChildren;
        bool areChildrenLoaded;
        bool areChildrenDisplayed;
        Thread threadIfRootPost;

        /// <summary>
        /// Gets or sets the thread if root post.
        /// This is only not null if this post is a root post
        /// </summary>
        /// <value>The thread if root post.</value>
        public Thread ThreadIfRootPost
        {
            get
            {
                return threadIfRootPost;
            }
            set
            {
                if (threadIfRootPost != value)
                {
                    threadIfRootPost = value;
                    OnPropertyChanged("ThreadIfRootPost");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether children are loaded.
        /// </summary>
        /// <value><c>true</c> if [are children loaded]; otherwise, <c>false</c>.</value>
        public bool AreChildrenLoaded
        {
            get
            {
                return areChildrenLoaded;
            }
            set
            {
                if (areChildrenLoaded != value)
                {
                    areChildrenLoaded = value;
                    OnPropertyChanged("AreChildrenLoaded");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether [are children displayed].
        /// </summary>
        /// <value>
        /// 	<c>true</c> if  children  are displayed; otherwise, <c>false</c>.
        /// </value>
        public bool AreChildrenDisplayed
        {
            get
            {
                return areChildrenDisplayed;
            }
            set
            {
                if (areChildrenDisplayed != value)
                {
                    areChildrenDisplayed = value;
                    OnPropertyChanged("AreChildrenDisplayed");
                }

                ShowChildren();
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance has children.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance has children; otherwise, <c>false</c>.
        /// </value>
        public bool HasChildren
        {
            get
            {
                return hasChildren;
            }
            set
            {
                if (hasChildren != value)
                {
                    hasChildren = value;
                    OnPropertyChanged("HasChildren");
                }
            }
        }

        /// <summary>
        /// Collection of child posts which get lazy loaded on demand
        /// </summary>
        public DispatchingObservableCollection<ThreadedPostViewModel> ChildPosts
        {
            get;
            private set;
        }

        /// <summary>
        /// Create a ThreadedPostViewModel for a given post
        /// </summary>
        /// <param name="post">Post to create container for</param>
        /// <param name="dispatcher">Dispatcher from the UI thread</param>
        public ThreadedPostViewModel(Post post, Dispatcher dispatcher) : base(post,dispatcher)
        {
            ChildPosts = new DispatchingObservableCollection<ThreadedPostViewModel>(dispatcher);

            using (var store = AppDataModel.Instance.ReadOnlyDataContext)
            {
                HasChildren = store.Posts.Any(p => p.ParentId == post.Id);
            }

            Post.ChildAdded += new Action<Guid>(PostChildAdded); 

        }



        /// <summary>
        /// Shows the children.
        /// </summary>
        private void ShowChildren()
        {
            if (!AreChildrenLoaded)
            {
                PopulateChildPosts();
            }

            foreach (var cp in ChildPosts)
            {
                cp.AreChildrenDisplayed = true;
            }
        }


        /// <summary>
        /// Loads all direct decendants of the this post containers Post object
        /// </summary>
        private void PopulateChildPosts()
        {
            lock (ChildPosts)
            {
                ChildPosts.Clear();

                using (var store = AppDataModel.Instance.ReadOnlyDataContext)
                {
                    var childPosts = from p in store.Posts
                                     where p.ParentId == Post.Id
                                     select p;

                    foreach (var p in childPosts)
                    {
                        ChildPosts.Add(new ThreadedPostViewModel(p, DispatcherUI));
                    }
                }
                AreChildrenLoaded = true;
            }
        }

        /// <summary>
        /// This post has a child added.
        /// </summary>
        /// <param name="childId">The child id.</param>
        private void PostChildAdded(Guid childId)
        {
            Post child = ObjectRegistry.GetPost(Post.ForumId, childId);
            if (child.ParentId != Post.Id) throw new ArgumentException("childId post is not a child of this post");

            lock (ChildPosts)
            {
                ChildPosts.Add(new ThreadedPostViewModel(child, DispatcherUI));
                HasChildren = true;
            }
        }


    }
}
